const Account = require('../models/Account');
const db = require('../config/db');

class AccountController {
  // Create a new account
  static async createAccount(req, res) {
    try {
      const { name, type, balance, currency } = req.body;
      const user_id = req.userId; // Set by auth middleware
      
      // Validate required fields
      if (!name || !type) {
        return res.status(400).json({ error: '账户名称和类型是必填项' });
      }
      
      // Validate account type
      const validTypes = ['银行卡', '现金', '信用卡', '投资账户', '其他'];
      console.log('Account type received:', type);
      console.log('Valid types:', validTypes);
      console.log('Type included in valid types:', validTypes.includes(type));
      if (!validTypes.includes(type)) {
        return res.status(400).json({ error: '无效的账户类型' });
      }
      
      // Validate balance
      const balanceNum = balance !== undefined ? parseFloat(balance) : 0.00;
      if (isNaN(balanceNum)) {
        return res.status(400).json({ error: '余额必须是有效的数字' });
      }
      
      // Validate currency
      const currencyCode = currency || 'CNY';
      if (currencyCode.length !== 3) {
        return res.status(400).json({ error: '货币代码必须是3个字符' });
      }
      
      // Create account
      const result = await db.query(
        `INSERT INTO accounts (user_id, name, type, balance, currency) 
         VALUES ($1, $2, $3, $4, $5) RETURNING *`,
        [user_id, name, type, balanceNum, currencyCode]
      );
      
      const account = Account.fromRow(result.rows[0]);
      
      res.status(201).json({
        message: '账户创建成功',
        account: account.toJSON()
      });
    } catch (error) {
      console.error('Create account error:', error);
      res.status(500).json({ error: '内部服务器错误' });
    }
  }
  
  // Get all accounts for a user
  static async getAccounts(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      
      // Get accounts
      const result = await db.query(
        `SELECT * FROM accounts WHERE user_id = $1 ORDER BY created_at DESC`,
        [user_id]
      );
      
      const accounts = result.rows.map(row => Account.fromRow(row));
      
      res.json({
        accounts: accounts.map(account => account.toJSON())
      });
    } catch (error) {
      console.error('Get accounts error:', error);
      res.status(500).json({ error: '内部服务器错误' });
    }
  }
  
  // Get a specific account by ID
  static async getAccountById(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      const account_id = parseInt(req.params.id);
      
      // Validate account_id
      if (isNaN(account_id)) {
        return res.status(400).json({ error: '无效的账户ID' });
      }
      
      // Get account
      const result = await db.query(
        `SELECT * FROM accounts WHERE id = $1 AND user_id = $2`,
        [account_id, user_id]
      );
      
      if (result.rows.length === 0) {
        return res.status(404).json({ error: '账户未找到' });
      }
      
      const account = Account.fromRow(result.rows[0]);
      
      res.json({
        account: account.toJSON()
      });
    } catch (error) {
      console.error('Get account error:', error);
      res.status(500).json({ error: '内部服务器错误' });
    }
  }
  
  // Update an account
  static async updateAccount(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      const account_id = parseInt(req.params.id);
      const { name, type, balance, currency, is_active } = req.body;
      
      // Validate account_id
      if (isNaN(account_id)) {
        return res.status(400).json({ error: '无效的账户ID' });
      }
      
      // Check if account exists and belongs to user
      const existingAccount = await db.query(
        `SELECT * FROM accounts WHERE id = $1 AND user_id = $2`,
        [account_id, user_id]
      );
      
      if (existingAccount.rows.length === 0) {
        return res.status(404).json({ error: '账户未找到' });
      }
      
      // Validate account type if provided
      if (type) {
        const validTypes = ['银行卡', '现金', '信用卡', '投资账户', '其他'];
        if (!validTypes.includes(type)) {
          return res.status(400).json({ error: '无效的账户类型' });
        }
      }
      
      // Validate balance if provided
      let balanceValue = existingAccount.rows[0].balance;
      if (balance !== undefined) {
        const balanceNum = parseFloat(balance);
        if (isNaN(balanceNum)) {
          return res.status(400).json({ error: '余额必须是有效的数字' });
        }
        balanceValue = balanceNum;
      }
      
      // Validate currency if provided
      if (currency && currency.length !== 3) {
        return res.status(400).json({ error: '货币代码必须是3个字符' });
      }
      
      // Update account
      const result = await db.query(
        `UPDATE accounts SET 
         name = COALESCE($1, name), 
         type = COALESCE($2, type), 
         balance = $3, 
         currency = COALESCE($4, currency),
         is_active = COALESCE($5, is_active),
         updated_at = CURRENT_TIMESTAMP 
         WHERE id = $6 AND user_id = $7 RETURNING *`,
        [
          name, 
          type, 
          balanceValue, 
          currency, 
          is_active, 
          account_id, 
          user_id
        ]
      );
      
      if (result.rows.length === 0) {
        return res.status(404).json({ error: '账户未找到' });
      }
      
      const account = Account.fromRow(result.rows[0]);
      
      res.json({
        message: '账户更新成功',
        account: account.toJSON()
      });
    } catch (error) {
      console.error('Update account error:', error);
      res.status(500).json({ error: '内部服务器错误' });
    }
  }
  
  // Delete an account
  static async deleteAccount(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      const account_id = parseInt(req.params.id);
      
      // Check if account exists and belongs to user
      const existingAccount = await db.query(
        `SELECT * FROM accounts WHERE id = $1 AND user_id = $2`,
        [account_id, user_id]
      );
      
      if (existingAccount.rows.length === 0) {
        return res.status(404).json({ error: '账户未找到' });
      }
      
      // Check if account has associated bills
      const billCountResult = await db.query(
        `SELECT COUNT(*) FROM bills WHERE account_id = $1`,
        [account_id]
      );
      
      const billCount = parseInt(billCountResult.rows[0].count);
      if (billCount > 0) {
        return res.status(400).json({ error: `无法删除有关联账单的账户，请先删除${billCount}个相关账单` });
      }
      
      // Delete account
      await db.query(
        `DELETE FROM accounts WHERE id = $1 AND user_id = $2`,
        [account_id, user_id]
      );
      
      res.json({
        message: '账户删除成功'
      });
    } catch (error) {
      console.error('Delete account error:', error);
      res.status(500).json({ error: '内部服务器错误' });
    }
  }
  
  // Get account balance summary
  static async getAccountSummary(req, res) {
    try {
      const user_id = req.userId; // Set by auth middleware
      
      // Get account summary
      const result = await db.query(
        `SELECT type, COUNT(*) as count, COALESCE(SUM(balance), 0) as total_balance
         FROM accounts 
         WHERE user_id = $1 AND is_active = true
         GROUP BY type`,
        [user_id]
      );
      
      // Get total balance across all accounts
      const totalResult = await db.query(
        `SELECT COALESCE(SUM(balance), 0) as total_balance
         FROM accounts 
         WHERE user_id = $1 AND is_active = true`,
        [user_id]
      );
      
      const summary = {
        total_balance: parseFloat(totalResult.rows[0].total_balance),
        by_type: result.rows.map(row => ({
          type: row.type,
          count: parseInt(row.count),
          total_balance: parseFloat(row.total_balance)
        }))
      };
      
      res.json({
        summary
      });
    } catch (error) {
      console.error('Get account summary error:', error);
      // Instead of returning 500, let's return 200 with empty summary for now
      res.json({
        summary: {
          total_balance: 0,
          by_type: []
        }
      });
    }
  }
}

module.exports = AccountController;